package com.xj.server;


import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
@EnableScheduling
@Slf4j
public class ExecuteCommandServer {
   final static boolean IS_WINDOWS=System.getProperty("os.name").toLowerCase().contains("windows");

    public static boolean commandExec(String[] args) {
        Runtime runtime = Runtime.getRuntime();
        List<String> commands = new ArrayList<>();
        if (!IS_WINDOWS){
            commands.addAll(Arrays.asList("/bin/sh", "-c"));
        } else {
            commands.addAll(Arrays.asList("cmd", "/c"));
        }
        commands.add(String.join(" ", args));
        try {
            Process exec = runtime.exec(commands.toArray(new String[0]));
            BufferedReader  reader=new BufferedReader(new InputStreamReader(exec.getInputStream()));
             String line;
             while((line=reader.readLine())!=null){
                 log.info(line);
             }
        //     exec.waitFor();
         //   int  exited = exec.exitValue();
            boolean exited = exec.waitFor(3, TimeUnit.MINUTES);
           if (exited){
               exec.destroy();
           }
            return exec.exitValue() == 0;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


  @Scheduled(cron = "${databaseBackTask}")
  public void    executRestart()  throws Exception{
        String[]  command=   {"net","stop","ufnet" };
      Runtime runtime = Runtime.getRuntime();
      List<String> commands = new ArrayList<>();
       commands.addAll(Arrays.asList("cmd", "/c"));
       commands.add(String.join(" ", command));
       Process process = runtime.exec(commands.toArray(new String[0]));

       Thread.sleep(5000);
       PrintWriter out = new PrintWriter(process.getOutputStream());
      String cmd ="Y"; //你的cmd命令
      out.write(cmd); //输入你的命令
      out.flush(); //写到控制台
      BufferedReader  reader=new BufferedReader(new InputStreamReader(process.getInputStream()));
      String line;
      while((line=reader.readLine())!=null){
          log.info(line);
      }
      process.waitFor();
      int  exited = process.exitValue();
      log.info("stop  ufnet ,result={}",exited);
       int i=0;
       command[1]=  "start";
       while(i<5){
           Boolean result2=   commandExec(command);
           log.info("第{}次执行start net，result={}",i,result2);
          if(result2){
              break;
          }
           Thread.sleep(9000);
          i++;
       }



  }

}
